package com.dede.locallib;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 通过app_process运行java进程的demo
 * <p>
 * 在jar包配置main入口
 * Main-Class: com.dede.locallib.HelloWorld
 * <p>
 * 将jar包打为dex包
 * dx --dex --output=dex.dex locallib.jar
 * <p>
 * 将dex包导入手机
 * <p>
 * 设置Class Path
 * export CLASSPATH=/storage/emulated/0/dex.dex
 * <p>
 * 开启进程
 * exec app_process /storage/emulated/0 com.dede.locallib.HelloWorld
 */
public class HelloWorld {

    public static void main(String... args) {
        System.out.println("Hello World!");
        log("haha", "Hello World!");

        try {
            Class<?> iDmSClass = Class.forName("android.service.dreams.IDreamManager$Stub");
            Class<?> iBinderClass = Class.forName("android.os.IBinder");
            Method asInterfaceMethod = iDmSClass.getMethod("asInterface", iBinderClass);
            Class<?> smClass = Class.forName("android.os.ServiceManager");
            Method getServiceMethod = smClass.getMethod("getService", String.class);
            Object iBinder = getServiceMethod.invoke(null, "dreams");

            Object dream = asInterfaceMethod.invoke(null, iBinder);

            Method dreamMethod = dream.getClass().getMethod("dream");
            dreamMethod.invoke(dream);
        } catch (ClassNotFoundException |
                NoSuchMethodException |
                IllegalAccessException |
                InvocationTargetException e) {
            e.printStackTrace();
            log("exception", e.getMessage());
            System.out.println("exception");
        }
    }

    public static void log(String tag, String msg) {
        try {
            Class<?> logClass = Class.forName("android.util.Log");
            Method method = logClass.getMethod("i", String.class, String.class);
            method.invoke(null, tag, msg);
        } catch (ClassNotFoundException |
                NoSuchMethodException |
                IllegalAccessException |
                InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
